#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>

using namespace std;

int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

void dfs(vector<vector<int> > &matrix, int i, int j)
{
    if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size()) return;
    if (!matrix[i][j]) return;
    matrix[i][j] = 0;
    for (int k = 0; k < 4; k++)
	dfs(matrix, i + dx[k], j + dy[k]);
}


int getMaxComponent(vector<vector<int> > &matrix)
{
    int cnt = 0;
    for (int i = 0; i < matrix.size(); i++) {
	for (int j = 0; j < matrix[0].size(); j++) {
	    if (matrix[i][j]) {
		cnt++;
		dfs(matrix, i, j);
	    }
	}
    }
    return cnt;
}

int main(int argc, char **argv)
{
    for (int cnt = 0; cnt < 10; cnt++) {
	int m = rand()%10 + 1;
	int n = rand()%10 + 1;
	vector<vector<int> > matrix(m, vector<int>(n, 0));
	for (int i = 0; i < m; i++) {
	    for (int j = 0; j < n; j++) {
		matrix[i][j] = rand()%2;
		cout << matrix[i][j] << " ";		
	    }
	    cout << endl;
	}	
	cout << "Max component is " << getMaxComponent(matrix) << endl;
	cout << endl;
	getchar();
    }
}
